package edu.sctu.zhu.controller;

import edu.sctu.zhu.bean.Category;
import edu.sctu.zhu.bean.Image;
import edu.sctu.zhu.dao.CategoryDao;
import edu.sctu.zhu.dao.FansDao;
import edu.sctu.zhu.dao.ImageDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 对页面进行操作
 * Created by zhu on 2015/11/11.
 */
@Controller
public class IndexController {

    @Autowired
    private FansDao fansDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private CategoryDao categoryDao;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Category> getIndex() {
        return null;
    }

    @RequestMapping(value = "/myAdmin/test", method = RequestMethod.GET)
    public String getAdmin() {

        return "myAdmin/test";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getlogin() {

        return "login";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String getupload() {

        return "upload";
    }


    @Autowired
    private ServletContext servletContext;

    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ModelAndView upload(ServletRequest request,
                               HttpSession httpSession
    ) throws IOException {

        ModelAndView modelAndView = new ModelAndView();
                if (request instanceof MultipartHttpServletRequest) {

                    Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();

                    Image image;

                    for (MultipartFile multipartFile : fileMap.values()) {

                        image = getUploadedFileInfo(multipartFile);

                        imageDao.save(image);


                        saveFileToLocalDisk(multipartFile, image.getImageName());
                    }

                modelAndView.setViewName("/login");

            }

        return modelAndView;
    }

    @RequestMapping(value = "/loginJudge", method = RequestMethod.GET)
    public String loginJudge() {

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()

                .getAuthentication()

                .getPrincipal();
       for (GrantedAuthority grantedAuthority:userDetails.getAuthorities()){
           if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")){
               return "/back_stage_anagement/mmt_admin/admin_index";
           }else if (grantedAuthority.getAuthority().equals("ROLE_SELLER")){
               return "/back_stage_anagement/seller/upload";
           }else {
               return "loginerror";
           }
       }

        return "loginerror";

    }



    private Image getUploadedFileInfo(MultipartFile multipartFile) throws IOException {

        Image image = new Image();
        String s = UUID.randomUUID().toString();

        String[] strings = multipartFile.getContentType().split("/");

        s = s + "."+strings[1];

        image.setImageName(s);
        image.setImageSize(String.valueOf(multipartFile.getSize()));
        image.setImageType(multipartFile.getContentType());
        image.setUrl("/resources/image/"+s);

        return image;
    }

    private void saveFileToLocalDisk(MultipartFile multipartFile,String imageName) throws IOException,
            FileNotFoundException {

        String outputFileName = getOutputFilename(imageName);


        FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName));
    }

    private String getOutputFilename(String imageName) throws IOException {

//        System.out.println("/resources/image/" + multipartFile.getOriginalFilename());


        return servletContext.getRealPath("/resources/image/" + imageName);

    }
}
